package com.bigData.main.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

@RestController
@RequestMapping("/api/file")
public class FileUploadController {
    private static final Path TEMP_DIR = Paths.get(System.getProperty("java.io.tmpdir"), "car_uploads");
    private static final List<Path> tempFiles = Collections.synchronizedList(new ArrayList<>());

    // 添加临时文件路径到静态列表
    public static synchronized void addTempFile(Path file) {
        tempFiles.add(file);
    }

    // 获取临时文件列表
    public static List<Path> getTempFiles() {
        return new ArrayList<>(tempFiles);
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("code") String code) {
        if (file == null || file.isEmpty()) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件为空");
            return ResponseEntity.status(400).body(error);
        }

        if (!"123456".equals(code)) { // 验证对接码
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "对接码不正确");
            return ResponseEntity.status(403).body(error);
        }

        try {
            // 将文件暂存到临时目录
            Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"));
            Path tempFile = Files.createTempFile(tempDir, "upload_", "_" + System.currentTimeMillis());
            Files.copy(file.getInputStream(), tempFile, StandardCopyOption.REPLACE_EXISTING);

            // 将临时文件路径添加到静态列表中
            addTempFile(tempFile);

            Map<String, String> response = new HashMap<>();
            response.put("status", "temp_success");
            response.put("message", "文件已暂存");
            response.put("tempPath", tempFile.toString());

            return ResponseEntity.ok(response);
        } catch (IOException e) {
            Map<String, String> error = new HashMap<>();
            error.put("status", "error");
            error.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}